using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.ResourceManagement.ResourceProviders;

public class CheckAssetsUpdate : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        //Addressables.LoadAssetAsync<GameObject>("Shou").Completed += LoadAssets_Completed;
        
        StartCoroutine(FetchRemoteLabelDownloadSize());
    }

    private IEnumerator FetchRemoteLabelDownloadSize()
    {
        AsyncOperationHandle<long> downloadSizeHandle = Addressables.GetDownloadSizeAsync("ALL");
        yield return downloadSizeHandle;
        
        if (downloadSizeHandle.Status == AsyncOperationStatus.Succeeded)
        {
            long downloadSize = downloadSizeHandle.Result;
            Debug.Log("Download size: " + downloadSize);
            if (downloadSize <= 0)
            {
                Debug.Log("没有更新");
            }
            else
            {
                Debug.Log("有更新");
                //开始一个协程，下载更新
                StartCoroutine(DownloadDependencies());
            }
            
            //我想把标签是tu的资源全部都加载出来
            // Addressables.LoadAssetsAsync<GameObject>("tu", null, (result) =>
            // {
            //     foreach (var r in result)
            //     {
            //         var go = Instantiate(r);
            //         go.AddComponent<Player>();
            //     }
            // });  
            
            
            // Addressables.LoadAssetsAsync<GameObject>("BG", null, Addressables.MergeMode.Union).Completed += LoadAssets_Completed;
            // Addressables.LoadAssetsAsync<GameObject>("BG", null)
            //     .Completed += LoadAssets_Completed;
            // Debug.Log("开始加载BG资源");

            EnterGame();

            // AsyncOperationHandle<SceneInstance> loadSceneAsync = Addressables.LoadSceneAsync("MainScene");
            // loadSceneAsync.Completed += (op) =>
            // {
            //     if (loadSceneAsync.Status == AsyncOperationStatus.Succeeded)
            //     {
            //         Debug.Log("加载场景成功");
            //         
            //     }
            //     else
            //     {
            //         Debug.Log("加载场景失败");
            //     }
            // };
        }
        else
        {
            Debug.Log("获取下载大小失败");
        }
        
        Addressables.Release(downloadSizeHandle);
    }

    private IEnumerator DownloadDependencies()
    {
        //从addressables下载更新
        AsyncOperationHandle downloadHandle = Addressables.DownloadDependenciesAsync("ALL");
        while (!downloadHandle.IsDone)
        {
            //显示下载进度，当前下载大小/总下载大小
            var progress = downloadHandle.PercentComplete;
            Debug.Log("下载进度: " + progress);
            
            var status = downloadHandle.GetDownloadStatus();
            Debug.Log("下载状态: " + status.ToString());
            
            var downloadedBytes = status.DownloadedBytes;
            var totalBytes = status.TotalBytes;
            var progress2 = (float)downloadedBytes / totalBytes;
            Debug.Log("下载进度2: " + progress2);
            Debug.Log($"当前下载：{Mathf.Round(downloadedBytes / 1048579f * 100) / 100}M / 总大小：{Mathf.Round(totalBytes / 1048579f * 100) / 100}M ，进度：{progress2:P2}");
            Debug.Log($"下载百分比: {status.Percent}");

            yield return null;
        }
        if (downloadHandle.Status == AsyncOperationStatus.Succeeded)
        {
            Debug.Log("下载成功");
            Addressables.Release(downloadHandle);
        }
        else
        {
            Debug.Log("下载失败");
        }
        
    }


    void LoadAssets_Completed(AsyncOperationHandle<IList<GameObject>> obj)
    {
        
        if (obj.Status == AsyncOperationStatus.Succeeded)
        {
            // 获取加载的所有 GameObjects。
            IList<GameObject> loadedGameObjects = obj.Result;
            
            //获取父物体下面的Canvas
            var canvas = GameObject.Find("Canvas");

            // 处理加载的 GameObjects。
            foreach (var go in loadedGameObjects)
            {
                // 例如，实例化每个 GameObject。
                //实例化并且设置位置不一样
                Instantiate(go,new Vector3(Random.Range(-5, 5), Random.Range(-2, 5), 0), Quaternion.identity,canvas.transform);

            }
        }
        else
        {
            Debug.LogError("Failed to load assets: " + obj.OperationException);
        }
        
        
        // 记得释放句柄以避免内存泄漏。
        // Addressables.Release(obj);
        
        
        // var a = Instantiate(obj.Result);
        // a.AddComponent<Player>();
    }
    
    //进入游戏
    private async void EnterGame()
    {
        Debug.Log("加载HotUpdate.dll");
        //跳转到游戏界面
        var loadDllAsync = Addressables.LoadAssetAsync<TextAsset>("HotUpdate.dll");
        await loadDllAsync.Task;
        Assembly hotUpdateDll = Assembly.Load(loadDllAsync.Result.bytes);
        Debug.Log("跳转到游戏界面");
        //用addressables加载场景
        AsyncOperationHandle<SceneInstance> lastSceneHandle = Addressables.LoadSceneAsync("MainScene"); 
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
